
#include <string.h>
#include <stdio.h>
#include <STDLIB.H>
#include "util.h"
#include "sysutil.h"

extern void DispErrorMsg(const BYTE *aMsg);

int is_leap(int q){
	if(q%4==0&&q%100!=0) return 1;
	if(q%400==0) return 1;
	else return 0;
}

struct Date{
	int year;
	int month;
	int day;
};

struct Date NextDate(int x,int y,int z){
	struct Date Date1;
	Date1.year=x;
	Date1.month=y;
	Date1.day=z;
//deal with Dce,if day equals 31 then year plus one,and reset month and day!
	if(y==12){
		if(z==31){
			Date1.year=Date1.year+1;
			Date1.month=1;
			Date1.day=1;
		}
		else{
			Date1.day=Date1.day+1;
		}
	}
//deal with Feb,considering the years!
	if(y==2){
		if(is_leap(x)){
			if(z==29){
			Date1.day=1;
			Date1.month=Date1.month+1;
			}
			else Date1.day=Date1.day+1;
		}
		else{
			if(z==28){
			Date1.day=1;
			Date1.month=Date1.month+1;
			}
			else Date1.day=Date1.day+1;
		}
	}
//deal with April,June,Sep,Nove
	if(y==4||y==6||y==9||y==11){
		if(z==30){
			Date1.day=1;
			Date1.month=Date1.month+1;
		}
		else{
			Date1.day=Date1.day+1;
		}
	}
//deal with Jan,Mar,May,July,Aug,Oct
	if(y==1||y==3||y==5||y==7||y==8||y==10){
		if(z==31){
		    Date1.day=1;
			Date1.month=Date1.month+1;
		}
		else Date1.day=Date1.day+1;   
	}
   return Date1;
}

int legal(int yea,int mont,int da)
{
   if (yea<=0) {
		DispErrorMsg("Error!year must over 0!");
		return 0;
	}

    if(mont<=0||mont>12) {
		DispErrorMsg("Error!month must between 0 and 12!");
		return 0;
	}

	if(da<=0||da>31) {
		DispErrorMsg("Error!day must between 0 and 31!");
		return 0;
	}

	if(mont==2 && is_leap(yea)){
		if(da>29){
			DispErrorMsg("Error! February of the leap year must less then 30 days!");
			return 0;
		}
	  }
	if(mont==2 && !(is_leap(yea))){
    if(da>28) {
			DispErrorMsg("Error! February of the no_leap year must less then 29 days!");
      return 0;
    }
  }
  if(mont==1||mont==3||mont==5||mont==7||mont==8||mont==10){
    if(da>31) {
			DispErrorMsg("Error! the day must less then 32!");
      return 0;
    }
  }
  if (mont==4||mont==6||mont==9||mont==11) {
    if(da>30) {
			DispErrorMsg("Error! the day must less then 31!");
      return 0;
    }
  }
  
  return 1;
}

int GetNextDate(char *cur_date,char *next_date)
{
  int day,month,year;
  struct Date Date2;
  char tmp_buf[10];
  char tmp_date[8];

  memset(tmp_buf,0x00,sizeof(tmp_buf));
  memcpy(tmp_buf,cur_date,4);
  year = atoi(tmp_buf);

  memset(tmp_buf,0x00,sizeof(tmp_buf));
  memcpy(tmp_buf,&cur_date[4],2);
  month = atoi(tmp_buf);

  memset(tmp_buf,0x00,sizeof(tmp_buf));
  memcpy(tmp_buf,&cur_date[6],2);
  day = atoi(tmp_buf);
  
  if (legal(year,month,day))
  { 
    Date2=NextDate(year,month,day);
    memset(tmp_date,' ',sizeof(tmp_date));
    sprintf(tmp_date,"%04d%02d%02d",Date2.year, Date2.month,Date2.day);
    memcpy(next_date,tmp_date,8);
    return 1;
  }
  
  return 0;
}
